<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ChannelCode\Logic;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Medium\Contract\MediumContract;
use MoChat\App\WorkContact\Contract\WorkContactTagContract;
use MoChat\App\WorkContact\Contract\WorkContactTagGroupContract;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeContract;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeGroupContract;
use MoChat\Plugin\Greeting\Action\Dashboard\Traits\MediumTrait;

/**
 * 渠道码列表.
 *
 * Class ShowLogic
 */
class ShowLogic
{
    use MediumTrait;

    /**
     * 标签分组表.
     * @Inject
     * @var WorkContactTagGroupContract
     */
    protected $workContactTagGroupService;

    /**
     * 标签表.
     * @Inject
     * @var WorkContactTagContract
     */
    protected $workContactTagService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * 渠道码表.
     * @Inject
     * @var ChannelCodeContract
     */
    private $channelCode;

    /**
     * 渠道码分组表.
     * @Inject
     * @var ChannelCodeGroupContract
     */
    private $channelCodeGroup;

    /**
     * 员工表.
     * @Inject
     * @var WorkEmployeeContract
     */
    private $workEmployee;

    /**
     * 部门表.
     * @Inject
     * @var WorkDepartmentContract
     */
    private $workDepartment;

    /**
     * 素材库表.
     * @Inject
     * @var MediumContract
     */
    private $medium;

    /**
     * 参数.
     * @var array
     */
    private $params;

    public function handle(array $params)
    {
        $this->params = $params;

        return $this->getInfo();
    }

    /**
     * 返回信息.
     * @return array
     */
    private function getInfo()
    {
        $info = $this->channelCode->getChannelCodeById((int) $this->params['channelCodeId']);
        if (empty($info)) {
            return [];
        }
        $workContactTagList = $this->getWorkContactTagList(Json::decode($info['tags'], true), user()['corpIds'][0]);
        $info['contactRemark'] = ! empty($info['contactRemark']) ? $info['contactRemark'] : '{"type": 1, "remark": "", "status": 0}';
        $info['closeWords'] = ! empty($info['closeWords']) ? $info['closeWords'] : '{"words": [], "status": 0}';
        // 基础信息
        $baseInfo = [
            'groupId' => $info['groupId'],
            'groupName' => ! empty($this->getGroup($info['groupId'])) ? $this->getGroup($info['groupId'])['name'] : '未分组',
            'name' => $info['name'],
            'autoAddFriend' => $info['autoAddFriend'],
            'tags' => Json::decode($info['tags'], true),
            'fullTags' => $this->getTags(Json::decode($info['tags'], true)),
            'corpTags' => $workContactTagList['tagGroupAllList'] ?? [],
            'contactRemark' => Json::decode($info['contactRemark']),
            'contactDescription' => $info['contactDescription'],
        ];
        $drainageEmployee = Json::decode($info['drainageEmployee']);
        if (! empty($drainageEmployee['addMax']['employees'])) {
            foreach ($drainageEmployee['addMax']['employees'] as $k => $v) {
                $employee = $this->workEmployeeService->getWorkEmployeeById($v['id'], ['id', 'name', 'avatar']);
                $drainageEmployee['addMax']['employees'][$k]['avatar'] = empty($employee['avatar']) ? '' : file_full_url($employee['avatar']);
            }
        }

        return [
            'baseInfo' => $baseInfo,
            'drainageEmployee' => $drainageEmployee,
            'type' => $info['type'],
            'welcomeMessage' => $this->handleWelcome($info),
            'spanWelcomeStatus' => $info['spanWelcomeStatus'],
            'spanWelcome' => $this->handleSpanWelcome($info),
            'closeWords' => ! empty($info['closeWords']) ? Json::decode($info['closeWords']) : [],
        ];
    }

    private function getTags($tagIds): array
    {
        return $this->workContactTagService->getWorkContactTagsById($tagIds, ['id', 'name', 'contact_tag_group_id']);
    }

    /**
     * 处理欢迎语设置.
     * @param $info
     * @return mixed
     */
    private function handleSpanWelcome($info)
    {
        if (empty($info['spanWelcome'])) {
            return [];
        }
        $spanWelcome = Json::decode($info['spanWelcome'], true);
        foreach ($spanWelcome as &$value) {
            $value['content'] = [];
            if (! empty($value['mediumId'])) {
                $value['content'] = $this->handleMedium($value['mediumId']);
            }
        }
        unset($value);

        return $spanWelcome;
    }

    /**
     * 处理欢迎语设置.
     * @param $info
     * @return mixed
     */
    private function handleWelcome($info)
    {
        if (empty($info['welcomeMessage'])) {
            return [];
        }
        $spanWelcome = Json::decode($info['welcomeMessage'], true);
        $spanWelcome['content'] = [];
        if (! empty($spanWelcome['mediumId'])) {
            $spanWelcome['content'] = $this->handleMedium($spanWelcome['mediumId']);
        }
        if (! isset($spanWelcome['mediumId'])) {
            $spanWelcome['mediumId'] = [];
        }
        if (! isset($spanWelcome['words'])) {
            $spanWelcome['words'] = '';
        }

        return $spanWelcome;
    }

    /**
     * 获取渠道码分组信息.
     * @param $groupId
     * @return array
     */
    private function getGroup($groupId)
    {
        $res = $this->channelCodeGroup->getChannelCodeGroupById((int) $groupId, ['name']);
        if (empty($res)) {
            return [];
        }

        return $res;
    }

    /**
     * @param array $workContactTagIds 客户标签ID数组
     * @param int $corpId 企业授信ID
     * @return array 响应数组
     */
    private function getWorkContactTagList(array $workContactTagIds, int $corpId): array
    {
        // 当前企业全部客户标签
        $tagList = $this->workContactTagService->getWorkContactTagsByCorpId([$corpId], ['id', 'name', 'contact_tag_group_id']);
        if (empty($tagList)) {
            return [];
        }
        // 客户标签分组
        $contactTagGroupIds = array_filter(array_unique(array_column($tagList, 'contactTagGroupId')));
        $tagGroupList = $this->workContactTagGroupService->getWorkContactTagGroupsById($contactTagGroupIds, ['id', 'group_name']);
        $tagGroupAllList = [
        ];
        if (! empty($tagGroupList)) {
            foreach ($tagGroupList as $tagGroup) {
                $tagGroupAllList[$tagGroup['id']] = [
                    'groupId' => $tagGroup['id'],
                    'groupName' => $tagGroup['groupName'],
                    'list' => [],
                ];
            }
        }
        // 标签分类处理
        $selectedTags = [];
        foreach ($tagList as $tag) {
            if (! isset($tagGroupAllList[$tag['contactTagGroupId']])) {
                continue;
            }
            in_array($tag['id'], $workContactTagIds, true) && $selectedTags[] = $tag['id'];
            $tagGroupAllList[$tag['contactTagGroupId']]['list'][] = [
                'tagId' => $tag['id'],
                'tagName' => $tag['name'],
                'isSelected' => in_array($tag['id'], $workContactTagIds, true) ? 1 : 2,
            ];
        }
        return [
            'tagGroupAllList' => array_values($tagGroupAllList),
            'selectedTags' => $selectedTags,
        ];
    }
}
